package com.example.lp.lpuicore.views.ui.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * Author by lp,on 2021/10/12/012,14:06.
 */
public class PaintView extends View {
    private Paint mPaint;
    private Canvas cacheCanvas;
    private Path mPath;
    private Bitmap mCachebBitmap;

    public PaintView(Context context) {
        super(context);
    }

    public PaintView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(4.0f);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.RED);

        mPath = new Path();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mCachebBitmap = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        //canvas绘制的内容，将会在这个mBufferBitmap内
        cacheCanvas = new Canvas(mCachebBitmap);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(mCachebBitmap, 0, 0, null);
    }

    private float mLastTouchX, mLastTouchY;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float eventX = event.getX();
        float eventY = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                mPath.moveTo(eventX, eventY);
                mLastTouchX = eventX;
                mLastTouchY = eventY;
                break;
            }

            case MotionEvent.ACTION_MOVE:
                mPath.quadTo(mLastTouchX, mLastTouchY, eventX, eventY);
                //在缓存里面绘制
                cacheCanvas.drawPath(mPath, mPaint);
                //重新绘制，会调用onDraw方法
                invalidate();
                mLastTouchX = eventX;
                mLastTouchY = eventY;
                break;
            case MotionEvent.ACTION_UP: {
                mPath.reset();
                break;
            }
        }
        return true;
    }
}
